#!/usr/bin/env python
# -*- coding:utf-8 -*-
#encoding=utf-8
'''
Created on 2013年12月12日

@author: daimin
'''
import filehandler
import nethandler
import comm

class Model:
    
    
    
    def __init__(self, **kwargs):
        self.__logfiles    = kwargs['logs'] if 'logs' in kwargs else []
        self._logkey       = kwargs['logkey'] if 'logkey' in kwargs else []
        self._modcfg       = kwargs['cfg'] if 'cfg' in kwargs else {}
        self._gamecfg      = self._modcfg['games'][self._logkey] if 'games' in self._modcfg  else self._modcfg
        self._pasday       = kwargs['pasday'] if 'pasday' in kwargs else {}
        self._gdata        = {}  ### 统计数据字典，最后要发送给统计服务器的数据
        self.req_params    = []   ### 请求参数
        self._curitem         = None ### 当前的Item
        self._alter_clear     = True ### #设置在每个处理每个文件后是否删除记录
        self.__more_interface = False
     
        self.spasday = self._pasday.strftime("%Y%m%d")
        if 'interfaces' in self._gamecfg and ('data_by_interface' not in self._gamecfg or self._gamecfg['data_by_interface'] == True):
            self._gdata = dict((k, {}) for (k, _) in self._gamecfg['interfaces'].items())
            self.__more_interface = True
        
    
    def run(self):
        for fpath in self.__logfiles:
            self.__fhandler = filehandler.FileHandler.get_instance(fpath, self._logkey)
            self.__fhandler.run_func(itcall=self._item_call, ctcall=self._count_call, aftcall=self.aftercall)
        self._request()
        self.__dorequest()
    
    def _item_call(self, line):
        """单调调用处理回调函数
        """
        pass
    
    def _count_call(self, data):
        """统计分析回调处理函数
        "" 每解析一个文件会调用一次这个接口
        "" 这里应该是汇总统计的结果
        """
        pass
    
    def aftercall(self):
        """每次过后的清理工作
        """
        if not self._alter_clear:
            return
        if self.__more_interface is None:
            map(lambda x:map(lambda y:x[1][y[0]].clear() if y[0].startswith('__') else y, x[1].items()), self._gdata.items())
        else:
            try:
                map(lambda item:map(lambda x:map(lambda y:x[1][y[0]].clear() if y[0].startswith('__') else y, x[1].items()),\
                                             item[1].items()), self._gdata.items())
            except:
                pass
                
    
    def curitem(self):
        """当前节点
        """
        return self._curitem

    
    def _request(self):
        """调用统计服务器接口
        "" 这个接口是所有的处理都完成后调用，通知统计服务器的
        """
        pass
            
    def __dorequest(self):
        ### key要进行md5
        #hash_key = self._modcfg['interfaces']['key'] = comm.md5(self._modcfg['key'])
        for (key, params) in self.req_params:
            params['id']  = self._gamecfg['interfaces'][key]['id']
            params['key'] = comm.md5(key)
            self.__reponse(res=nethandler.get(self._gamecfg['interfaces'][key]['interface'], **params))
    
    def __reponse(self, res):
        if res == '0':
            comm.getlogger().info('Request success!!')
        else:
            comm.getlogger().info('Request fail!!!')
            
class Interface:
    def __init__(self, **kwargs):
        self._data          = kwargs['data'] if 'data' in kwargs else None
        self._interface_cfg = kwargs['cfg'] if 'cfg' in kwargs else None
        self._params        = kwargs['param'] if 'param' in kwargs else None
        self._model         = kwargs['model'] if 'model' in kwargs else None
    
    def _set_cur_key(self, key, callback=None):
        self.__curkey = key
        if self.__curkey not in self._data:
            if callback is not None:
                callback(self.__curkey)
        self._curitem = self._data[self.__curkey]
        return self._curitem
    
    def countdata(self, data):
        pass
        
@comm.deco_log('logs')
def __init__run_parse(**kwargs):
    if 'games' in kwargs['cfg']:
        for game in kwargs['cfg']['games']:
            model     = kwargs['mod'][game]  if 'mod'  in kwargs and game in kwargs['mod'] else None
            model(**kwargs).run()
    else:
        kwargs['mod'](**kwargs).run()
     
    
